package main

import (
	"fmt"
	"sync"
)

var (
	sum int
	// mutex sync.Mutex
	mutex sync.RWMutex //
)

func main() {

	run()
}

func run() {
	var wg sync.WaitGroup

	// 因为要监控110个协程，所以设置计数器为110
	wg.Add(110)
	for i := 0; i < 100; i++ {
		go func() {
			// 计数器值减1
			defer wg.Done()
			add(10)
		}()
	}

	for i := 0; i < 10; i++ {
		go func() {
			// 计数器值减1
			defer wg.Done()
			fmt.Println("和为:", readSum())
		}()
	}
	// 一直等待，只要计数器值为0
	wg.Wait()
	// time.Sleep(2 * time.Second)
}

// 增加了一个读取sum的函数，便于演示并发
func readSum() int {
	mutex.Lock()
	defer mutex.Unlock()
	b := sum
	return b
}

func add(i int) {
	mutex.Lock()
	defer mutex.Unlock()
	sum += i
	// mutex.Unlock()
}
